package com.guangwei.example.handlertest;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.system.Os;
import android.util.Log;

public class MainActivity extends AppCompatActivity {
    private final static String TAG = "HandlerTest";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Log.i(TAG, "onCreate: PID = " + Os.getpid() + ", TID = " + Os.gettid());


    }

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            Log.i(TAG, "handleMessage: msg.what = " + msg.what);
            Log.i(TAG, "handleMessage: PID = " + Os.getpid() + ", TID = " + Os.gettid());

            switch (msg.what) {
                case 1:
                    Log.i(TAG, "handleMessage: do something here");
                    break;
                default:
                    break;
            }
        }
    };

    Handler backgroundHandler;

    @Override
    protected void onResume() {
        super.onResume();
        mHandler.sendEmptyMessage(1);

        HandlerThread backgroundHandlerThread = new HandlerThread("BackgroudHandlerThread");
        backgroundHandlerThread.start();
        backgroundHandler = new Handler(backgroundHandlerThread.getLooper()) {
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                Log.i(TAG, "background handleMessage: msg.what = " + msg.what);
                Log.i(TAG, "background handleMessage: PID = " + Os.getpid() + ", TID = " + Os.gettid());

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.i(TAG, "runOnUiThread: PID = " + Os.getpid() + ", TID = " + Os.gettid());
                    }
                });
            }
        };

        backgroundHandler.sendEmptyMessage(2);
    }
}